package com.mfz.common;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

/**
 * create by 2019-07-09.
 *
 * @author yimin
 */

public final class StringUtil {
    public static final String NEWLINE;

    static {
        // Determine the newline character of the current platform.
        String newLine;

        Formatter formatter = new Formatter();
        try {
            newLine = formatter.format("%n").toString();
        } catch (Exception e) {
            // Should not reach here, but just in case.
            newLine = "\n";
        } finally {
            formatter.close();
        }

        NEWLINE = newLine;
    }

    public static Map<String, Object> getParameter(JSONObject object, String name) {
        Map<String, Object> map = new HashMap<>();

        Object obj = object.get(name);

        if (obj instanceof JSONObject) {
            for (String string : ((JSONObject) obj).keySet()) {
                map.put(string,((JSONObject) obj).get(string));
            }
        } else {
            map.put(name, obj);
        }

        return map;
    }

    /**
     * 根据给定的编码，从文件中读取字符串
     *
     * @param configURL URL地址
     * @param code      指定文件的编码格式
     * @return 读取到的字符串
     */
    public static String getProperties(URL configURL, String code) {
        InputStream stream;
        URLConnection uConn;
        BufferedReader reader;
        StringBuilder builder = new StringBuilder();

        try {
            uConn = configURL.openConnection();
            uConn.setUseCaches(false);
            stream = uConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(stream, code);
            reader = new BufferedReader(inputStreamReader);
            String tempString;
            while ((tempString = reader.readLine()) != null) {
                builder.append(tempString).append(StringUtil.NEWLINE);
            }
            reader.close();

            return builder.toString();
        } catch (Exception e) {
            return null;
        }
    }
}